package jtools

import (
	"bufio"
	"bytes"
	"encoding/binary"
	"fmt"
	"io"
	"strings"

	"gitee.com/liaojin0910/jtools/models"
)

func TOut(i interface{}) {
	s, e := T2String(i)
	if e != nil {
		fmt.Println("Tout error")
	} else {
		fmt.Println(s)
	}
}

func T2String(i interface{}) (string, error) {
	sArr, e := T2StrArr(i)
	if e != nil {
		return "", e
	}

	return strings.Join(sArr, "\t"), nil
}

func T2StrArr(a interface{}) (sArr []string, err error) {
	tArr, e := T2Bytes(a)
	if e != nil {
		return nil, e
	}
	strArr := make([]string, 0)
	for _, item := range tArr {
		strArr = append(strArr, fmt.Sprintf("%.8b", item))
	}
	return strArr, nil

}

func THexOut(i interface{}) {
	s, e := T2HexString(i)
	if e != nil {
		fmt.Println("T hex out error")
	} else {
		fmt.Println(s)
	}
}

func T2HexString(i interface{}) (string, error) {
	sArr, e := T2HexArr(i)
	if e != nil {
		return "", e
	}

	return strings.Join(sArr, "\t"), nil
}

func T2HexArr(a interface{}) (sArr []string, err error) {
	tArr, e := T2Bytes(a)
	if e != nil {
		return nil, e
	}
	strArr := make([]string, 0)
	for _, item := range tArr {
		strArr = append(strArr, fmt.Sprintf("%.2x", item))
	}
	return strArr, nil

}

func T2Bytes(a interface{}) (byteArr []byte, err error) {

	var byteArray = bytes.NewBuffer([]byte{})
	e := binary.Write(byteArray, binary.BigEndian, a)

	if e != nil {
		return nil, e
	}
	return byteArray.Bytes(), nil
}

func G2md(r io.Reader) string {
	/**
	stat 状态
	0.没启动
	1.解析注释
	2.解析代码
	*/
	var stat = 0
	var buf bytes.Buffer
	br := bufio.NewReader(r)
	for {
		oldStat := stat
		line, _, err := br.ReadLine()

		if err == io.EOF {
			break
		}

		lineStr := string(line)
		lineStr = strings.TrimLeft(lineStr, " ")
		if strings.HasPrefix(lineStr, "/*") {
			stat = 1
		}
		if strings.HasPrefix(lineStr, "*/") {
			stat = 2
		}

		switch stat {
		case 0:
			continue
		case 1:
			if oldStat == 0 {
				continue
			}
			if oldStat == 2 {
				buf.WriteString("```\n")
				continue
			}
			buf.WriteString(lineStr + "\n")
		case 2:
			if oldStat == 1 {
				buf.WriteString("```\n")
				continue
			}

			buf.WriteString(lineStr + "\n")
		}

	}
	buf.WriteString("```\n")

	return buf.String()
}

func MakeHttp() *models.Jhttp {
	return models.MakeHttp()
}
